﻿using Conversive.PHPSerializationLibrary;
using FaceMqttClient;
using Furion;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Serilog;
using Serilog.Core;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Lxb.Model.config;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.WxaBusinessGetUserEncryptKeyResponse.Types;

namespace MqttClient.Jobs
{

    //[PeriodMinutes(10)]
    [PeriodSeconds(30)]
    [JobDetail(jobId: "设备状态通知", description: "设备状态通知", GroupName = "系统", Concurrent = false)]
    public class DevCheckJob : IJob
    {
        string pkey = "easywechat.kernel.access_token*";
       static  string key = "";
        private string token;
        private readonly WechatApiClientOptions options;
        private readonly ILogger loger;
        PhpSerializer ps = new PhpSerializer();
        public DevCheckJob(ILogger loger )
        {
            options = new WechatApiClientOptions()
            {
                AppId = "wx42a8bcc9d53bcf3b",
                AppSecret = "673321d209f6c3e3b4d8d9eb6fce56a6",
            };
            this.loger = loger;
        }


        public Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {

            var server = RedisHelper.GetServer("127.0.0.1", 6379);
            while (key.IsNullOrEmpty())
            {



                foreach (var akey in RedisHelper.GetLikeKeys(pkey))
                {
                    //  Console.WriteLine(key);
                    key = akey;
                    Console.WriteLine(akey);
                }
                Thread.Sleep(1000);

            }
            var dbredis = RedisHelper.GetDatabase();
            var str = (dbredis.StringGet(key));
            if (!String.IsNullOrEmpty(str))
            {


                var t = (Dictionary<object, object>)ps.Deserialize(str);
                if (t.ContainsKey("access_token"))
                {
                    token = t["access_token"].ToString();

                }
            }
            if (token.IsNullOrEmpty()) {
                return Task.CompletedTask;
            }

                Devchcek();
            return Task.CompletedTask;
        }


        /// <summary>
        ///  设备在线检测 10分钟一次
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        //[SpareTime(600000, "jobName3", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]

        public void Devchcek()
        {
//            Console.WriteLine("Devchcek " + DateTime.Now.ToString());
            //loger.Warning("Devchcek " + DateTime.Now.ToString());
            var h = DateTime.Now.Hour;
            if ((h < 6) || (h > 22))
            {

                return;

            }
            var options3 = App.GetOptionsMonitor<LxbOptions>();
            Console.WriteLine(options3);

            Scoped.Create((_, scope) =>
            {
                var services = scope.ServiceProvider;
                var dvck = services.GetService<DeviceCheck>();
                for (int i = 0; i < 2; i++)
                {


                    CgibinMessageTemplateSendRequest tplr = new();
                    foreach (var item in dvck.Getdevevent(i))
                    {


                        tplr.TemplateId = TplIds.设备状态;
                        tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
                        // 头
                        tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"{item.school} 设备状态发生变化" });
                        // 名
                        tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = item.name, Color = "#173177" });
                        // 状态
                        tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = item.state == 1 ? "在线" : "离线", Color = item.state == 1 ? "#FF0000" : "#173177" });
                        // 地点

                        // 备注
                        tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"发生时间{item.ctime}", Color = "#ff0000" });


#if DEBUG
                        tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
                tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8"; //oyXHL0kSA5RKTQ0C29JQwVdqm_lA
#endif

                        tplr.AccessToken = token;
                        //tplr.Url = "";



                        dvck.delesend(item);

                        var options3 = App.GetOptionsMonitor<LxbOptions>();
                        var client = new WechatApiClient(options);
                        foreach (var optid in options3.openids)
                        {
                            Console.WriteLine(optid + " 通知");
                            tplr.ToUserOpenId = optid;
                            client.ExecuteCgibinMessageTemplateSendAsync(tplr);
                        }
                    }
                }

            });

            //Console.WriteLine("校园通知" + count);
        }
    }
}
